<template>
	<div>
		<div class="top_border">
		  <!-- <FormPanel
			  :list="topFilterList"
        :cols="4"
        labelWidth="90"
			  :isSubmitBtn="false"
      /> -->
      <TopFilter
        ref="TopFilterss"
        :list="topFilterList"
        :cols="3"
        labelWidth="90"
        @filterChange="changeHandle"
      />
		</div>

		<FilterTable
	      ref="table"
	      :columns="columns"
	      :fetchapi="fetchApi"
	      :params="fetchParams"
        :datakey="'records'"
	      :onColumnsChange="columns => this.columns = columns"
	    >
	      <template slot="controls" slot-scope="props">
	        <el-button size="small" type="primary"  @click="addHandle">导出</el-button>
	      </template>
	    </FilterTable>

		<!--<BaseDialog
	      :visible.sync="visible2"
	      title="文件导出"
	      destroyOnClose
	      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
	    />-->

    	<Drawer
		  :visible.sync="visible"
		  title="销售订单明细"
      :width="1050"
      destroyOnClose
		>
		  <orderDetails :type="handleType" :rowData="formData" @close="closeHandler"></orderDetails>
		</Drawer>


	</div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import orderDetails from './orderDetails';

import { salesOrders, exportOrders,putSalesOrders } from '@/api/retail/salesmanage/salesorder';
import { vehicleConfiguration } from '@/api/retail/salesmanage/confirmcar'; //获取五级菜单
import { getUsersByPosition } from '@/api/retail/salesmanage/salesordermanage';
import { exportExcelFile } from '@/utils/index';
export default {
	name: 'salesorder',
	mixins: [dictionary],
	components: {
	    orderDetails
	},
	data() {
		return {
			topFilterList: this.createTopFilters(),
      fetchParams: {},
      visible: false,
      visible2: false,
      dialogTitle: '',
      fetchApi: salesOrders,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      conf:{ add: '新增', edit: '编辑', show: '显示' },
      querInfo: { //请求数据
        pageNum: 1,
        currentPage: 1,
        pageSize: 20,
        limit: 20
      },
      carNameItem:"",
		}
	},
  created (){
    this.init();
    this.getEmployeeList()
  },
	methods: {
    init (){
      vehicleConfiguration(0, {
        isUnlimited: 10041001
      }).then( res => {
        this.topFilterList.find(item => item.fieldName == 'carName').itemList = res.data;
      }).catch( err => {
        // console.log(err)
      })

    },
    createTopFilters (){
      return [
        {
        type: 'SELECT',
        label: '销售顾问',
        fieldName: 'consultant',
        placeholder: '请选择...',
        itemList: [],
      },
      {
        type: 'INPUT',
        label: '销售订单号',
        fieldName: 'viNo',
        placeholder: '请输入...'
      },
      {
        type: 'INPUT',
        label: '客户名称',
        fieldName: 'customerName',
        placeholder: '请输入...'
      },
      {
        type: 'INPUT_CASCADER',
        label: '产品配置',
        fieldName: 'carName',
        placeholder: '请选择...',
        options:{ titles: ['品牌', '车系', '车型', '配置', '颜色'] },
        change:(val,ref, item)=>{
          // console.log(val,"产品配置")
          // console.log(item,"产品配置item")
          this.carNameItem = item
        },
        itemList:[{
          text: '一级分类1',
          value: '1',
          children: []
        }],
      },
      {
        type: 'RANGE_DATE',
        label: '订单提交日期',
        fieldName: 'submitTimeStart|submitTimeEnd',
        placeholder: '请输入...'
      },
      ]
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>明细</el-button>
                <el-button size="mini" type="text" 
                disabled={
                props.row.viStatus == 14041010 ?true:false || 
                props.row.viStatus == 14041017 ?true:false ||
                props.row.viStatus == 14041011 ?true:false ||
                props.row.viStatus == 14041012 ?true:false } 
                onClick={() => this.deleteHandle(props.row)}>取消</el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '客户编号',
          dataIndex: 'customerNo',
          sorter: true,
          filter: true,
          width: 180,
          showOverflowTooltip:true,
          filterType: 'input',
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '手机号码',
          dataIndex: 'mobilePhone',
          showOverflowTooltip:true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultant',
          showOverflowTooltip:true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN号',
          dataIndex: 'salesVin',
          sorter: true,
          showOverflowTooltip:true,
          filter: true,
          width: 180,
          filterType: 'input'
        },
        {
          title: '产品代码',
          dataIndex: 'productCode',
          sorter: true,
          width: 180,
          showOverflowTooltip:true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          sorter: true,
          showOverflowTooltip:true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售指导价',
          dataIndex: 'directivePrice',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '销售单价',
          dataIndex: 'vehiclePrice',
          sorter: true,
          showOverflowTooltip:true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单状态',
          dataIndex: 'viStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('1404'),
          render: props => {
            return <span>{this.createDictText(props.row.viStatus, '1404')}</span>;
          }
        },
        {
          title: '出库状态',
          dataIndex: 'outStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('1415'),
          render: props => {
            return <span>{this.createDictText(props.row.outStatus, '1415')}</span>;
          }
        },
        {
          title: '预交车日期',
          dataIndex: 'deliveringDate',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input',
          render: props =>{
            return <span>{ this.formatDates(props.row.deliveringDate) } </span>
          }
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '颜色',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '开单日期',
          dataIndex: 'sheetCreateDate',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input',
          render: props =>{
            return <span>{ this.formatDates(props.row.sheetCreateDate) } </span>
          }
        },
        {
          title: '发票号',
          dataIndex: 'invoiceNo',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '开票日期',
          dataIndex: 'invoiceDate',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input',
          render: props =>{
            return <span>{ this.formatDates(props.row.invoiceDate) } </span>
          }
        },
        {
          title: '开票名称',
          dataIndex: 'invoiceName',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },
        {
          title: '开票联系人',
          dataIndex: 'invoiceLinkMan',
          sorter: true,
          showOverflowTooltip:true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '开票地址',
          dataIndex: 'invoiceAddress',
          sorter: true,
          showOverflowTooltip:true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '建档时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input',
          render: props =>{
            return <span>{ this.formatDates(props.row.createdAt) } </span>
          }
        },
        {
          title: '销售订单号',
          dataIndex: 'viNo', // soNo改为viNo
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        },

      ];
    },
		addHandle() {
      this.$refs.TopFilterss.SUBMIT_FORM();
      console.log(this.querInfo,this.fetchParams)
		  this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        exportOrders(this.fetchParams).then( response => {
          exportExcelFile(response.data,'销售订单');
          this.exportLoading = false;
        }).catch( err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
  // async exportOrderPc (){
    //   let res = await exportOrders ();
    //   console.log(res)
    //   if(res.resultCode == 200){
    //     console.log('成功')
    //   }
    // },
    formatDates (value) { //时间过滤
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == "") {
        return "";
      }
      var date = new Date(Number(value));
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + "-" + month + "-" + day;
    },
    detailHandle(row) { //查看明细事件
      this.visible = true;
      this.handleType = 'show';
      this.formData = row;
      // this.showHandler();
    },
    //取消
    deleteHandle(row){
      console.log(row,"取消")
      let params={
        recordVersion: row.recordVersion,
        soVinId:row.soVinId
      }
      putSalesOrders(params).then(res=>{
        if(res.resultCode == 200){
          this.$message({
            message: '取消成功',
            type: 'warning'
          });
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }
      })
    },
    showHandler() {
      this.dialogTitle = `购车因素${this.conf[this.handleType]}`;
      this.visible = true;
    },
    changeHandle(val) { //搜索事件
    // console.log(val.carName,"val.carName",val.carName.split(",").length)
      if(val.carName){
        let carNameValue = val.carName.split(",")[val.carName.split(",").length-1]
        let productId = ""
        this.carNameItem.forEach(x=>{
            if(x.value == carNameValue){
              productId = x.productId
            }
        })
        if(productId){
          val.carName+=`,${productId}`
        }
        let carNameProductId = ""
        val.carName.split(",").forEach(x=>{
            if(x != carNameValue){
              carNameProductId+=x+','
            }
        })
        // console.log(carNameProductId,"carNameProductId",carNameProductId.slice(0,carNameProductId.lastIndexOf(",")))
        val.carName = carNameProductId.slice(0,carNameProductId.lastIndexOf(","))
      }
      
      this.fetchParams = Object.assign({}, val,);
      this.querInfo = Object.assign({}, val);
    },


    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async getEmployeeList() {
      let params = {
        positionCodes: [10061015],
        menuId: 223001
      }
      const res = await getUsersByPosition(params);
      // console.log('销售顾问', res)
      if (res.resultCode === 200) {
        this.consultantList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.topFilterList.find(item => item.fieldName == 'consultant').itemList = this.consultantList;
      }
      // const res = await getSalesConsultant();
      // // console.log('销售顾问', res)
      // if (res.resultCode === 200) {
      //   this.topFilterList[0].itemList = res.data.map(x => ({ value: x.employeeNo, text: x.employeeName }));
      // }
    },



	},
	mounted() {
	   this.BaseTable = this.$refs.table.$refs.pageTable;
	}
}</script>

<style scoped="scoped" lang="less">

.top_border{
	border: 1px solid @borderColor;
	padding-top: 15px;
	margin-bottom: 15px;
}
</style>
